/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mobiubiq.directory.client.widget;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import org.kalmeo.kuix.core.Kuix;
import org.kalmeo.kuix.widget.Widget;

/**
 *
 * @author Marnix  Renne
 */
public class AudioPlayer extends Widget {

    public static final String AUDIOPLAYER_WIDGET_TAG = "audioplayer";
    private String source;
    private boolean autostart = false;

    public AudioPlayer() {
        super(AUDIOPLAYER_WIDGET_TAG);
    }

    public boolean setAttribute(String name, String value) {
        if ("src".equals(name)) {
            setSrc(value);
            return true;
        } else if ("autostart".equals(name)) {
            setAutostart(value);
            return true;
        } else {
            return super.setAttribute(name, value);
        }
    }

    public void setSrc(String value) {
        source = value;
    }

    public void setAutostart(String value) {
        if ("true".equals(value)) {
            autostart = true;
        } else {
            autostart = false;
        }
    }

    protected void onAdded(Widget parent) {
        super.onAdded(parent);
        if (autostart) {
            play();
        }
    }

    public void play() {
        HttpConnection connection = null;
        try {
            connection = (HttpConnection) Connector.open(source);
            String contentType = connection.getHeaderField("Content-Type");
            InputStream is = connection.openInputStream();
            String[] types = Manager.getSupportedContentTypes(null);
            System.out.println(types);
            Player player = Manager.createPlayer(is, contentType);

            player.realize();
            player.prefetch();
            player.start();
        } catch (Throwable e) {
            Kuix.alert(e);
        } finally {
            if(connection != null) {
                try {connection.close();} catch(IOException e){}
            }
        }
    }
}